<?php
/**
 * Created by laoyu.
 * User: hilaoyu@qq.com
 * Date: 2019/6/5
 * Time: 17:07
 */

namespace Hilaoyu\Utils\Drivers\Sms;


use Hilaoyu\LaravelExtend\Supports\Uuid;
use Hilaoyu\Utils\Traits\ErrorsTrait;
use Hilaoyu\Utils\UtilAes;
use Hilaoyu\Utils\UtilArr;
use Hilaoyu\Utils\UtilHttp;
use Hilaoyu\Utils\UtilRegex;
use Hilaoyu\Utils\UtilStr;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;

class Mozhe
{
    use ErrorsTrait;

    static $_license = [];
    protected $encryptor = null;
    protected $auth_id = null;
    protected $client = null;
    protected $config = [];

    public function __construct($config = [])
    {

        $this->setConfig($config);
    }

    public function setConfig($config = [])
    {
        $this->config = (array)$config;

        $this->auth_id = $this->GetLicense("auth_id");
        $this->client = new UtilHttp($this->GetLicense("basic_uri"));
        if (empty(static::$_license)) {
            $this->setError("无授权信息", "auth_info");
            return false;
        }

        $this->setEncryptor();
    }

    public function getConfig($key = '')
    {
        $key = trim($key);

        if ($key) {
            return UtilArr::get($this->config, $key);
        }

        return $this->config;
    }

    protected function licenseFilePath()
    {
        $license_path = $this->getConfig("license_path");
        return storage_path($license_path ?: 'system/ams_license.json');
    }

    protected function GetLicense($key = '')
    {
        $key = trim($key);
        if (empty(static::$_license)) {
            $licenseFile = $this->licenseFilePath();
            if (file_exists($licenseFile)) {
                try {
                    $content = file_get_contents($licenseFile);
                    $license = json_decode($content, true);
                    static::$_license = $license;
                } catch (\Exception $exception) {
                    $this->setError("授权文件解析失败");
                }
            }
        }

        return $key ? data_get(static::$_license, $key) : static::$_license;
    }

    protected function buildTplValue($content, $tpl = '')
    {

        if (empty($tpl)) {
            return UtilArr::toString($content);
        }

        $content = UtilStr::replace($tpl, (array)$content);

        return $content;
    }

    public function send($phone, $content, $tpl = '')
    {
        $phone = trim($phone);
        $tpl = trim($tpl);
//        $tpl = config('sms.config.tpl.'.$tpl);
        if (!$tpl){
            $this->setError('模板错误');
            return false;
        }

        if (!UtilRegex::isMobile($phone)) {
            $this->setError('手机号格式错误');
            return false;
        }

        if (!is_array($content)){
            $content = (array)$content;
        }

        $this->resultCache = null;

        $params = [];

        $data['mobile'] = $phone;
        if (UtilStr::startsWith($tpl, "TemplateKey-")) {
            $data['template_key'] = $tpl;
//            $data['template_paras'] = json_encode(array_values($content),JSON_UNESCAPED_UNICODE);
            $data['template_paras'] = array_values($content);
        } else {
            $data['content'] = $this->buildTplValue($content, $tpl);
        }
        $data['timestamp'] = Carbon::now()->unix();
        $data['_data_id'] = UtilStr::randString();
        $data['data_id'] = $data['_data_id'];
//        dump($data, UtilStr::startsWith($tpl, "TemplateKey-"), $tpl);
        if ($this->encryptor) {
            $data = $this->encryptor->encrypt($data);
            $params['data'] = $data;
        } else {
            $params = array_merge($params, $data);
        }

        $headers = ["AuthId"=>$this->auth_id];

//        dump($params, $headers);
        $result = $this->client->httpRequestJson("/sms/send-single", $params, "post", $headers);
        if (!$result) {
            $this->setError($this->client->getError());
            return false;
        }

        $result_data = data_get($result, 'data');
        if (is_string($result_data) && !empty($result_data)) {
            $result['data'] = $this->decrypt($result_data);
        }

        $this->resultCache = $result;
        $status = data_get($result, 'status');
        if (!$status) {
            $errors = data_get($result, 'errors');
            if (!empty($errors)) {
//                $this->setError("3121");
                $this->setError($errors);
            }
        }

        return $status;
    }

    protected function setEncryptor()
    {
        $this->encryptor = UtilAes::make($this->GetLicense('secret'));
    }
}
